package org.sky.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.log4j.Logger;
import org.sky.service.FileUtilService;
import org.sky.vo.FileVO;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.text.DecimalFormat;
import java.util.Date;

@Component("uploadFile")
@Scope("prototype")
public class UploadFileAction extends MyActionSupport implements ModelDriven<FileVO> {

    private final FileVO fileVO = new FileVO();
    private FileUtilService fileUtilService;

    private final static Logger logger = Logger.getLogger(UploadFileAction.class);

    //当前登录用户
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    private final String username = userDetails.getUsername();
    private static String savePathDir = "D:/KParty/upload_file/";

    @Override
    public String execute() throws Exception {

        // 得到保存上传文件的目录的真实路径
        File dir = new File(savePathDir);
        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        fileVO.setAuthor(username);
        fileVO.setUploadDir(savePathDir);//保存路径

        DecimalFormat df = new DecimalFormat("0.00");
        fileVO.setSize(Double.parseDouble(df.format(fileVO.getUpload().length() / 1024.0 / 1024.0)));  // 文件大小(Mb计算)

        int pos = fileVO.getUploadFileName().lastIndexOf(".");
        fileVO.setUploadContentType(fileVO.getUploadFileName().substring(pos + 1));//文件后缀名
        fileVO.setDate(new Date());//当前日期
        InputStream is = new FileInputStream(fileVO.getUpload());
        OutputStream os = new FileOutputStream(new File(dir, fileVO.getUploadFileName()));
        byte[] buf = new byte[1024];
        int len = -1;
        while ((len = is.read(buf)) != -1) {
            os.write(buf, 0, len);
        }

        is.close();
        os.close();

        if (fileUtilService.uploadFile(fileVO)) {
            fileVO.setResultMessage("{suc:1, msg:’上传成功!’}");
        } else {
            fileVO.setResultMessage("{suc:0, msg:’上传失败!’}");
        }
        return SUCCESS;
    }

    @Resource(name = "fileUtilServiceImpl")
    public void setFileUtilService(FileUtilService fileUtilService) {
        this.fileUtilService = fileUtilService;
    }

    @Override
    public FileVO getModel() {
        return fileVO;
    }

}
